//
//  HMProductListViewController.m
//  HMMarket
//
//  Created by maimaigo3 on 2017/5/12.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMProductListViewController.h"
#import "HomeCollectionViewCell.h"
#import "HMProductList.h"
#import "HMProductListCollectionViewCell.h"
#import "HttpBaseTool.h"
#import "HomeCategory.h"
#import "HMProductModel.h"
#import "HMSelectTitleView.h"
#import "HMSelectType.h"
#import "HMCartController.h"
#import "HMProductDetailViewController.h"
#import "HMSearchController.h"
#import "HMLastPro.h"
#import "HMLoginController.h"
#import "HMAddCartWithSize.h"
#import "HMNoDataReload.h"

@interface HMProductListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, HMProductListDelegate, HMSelectTitleViewDelegate, HMSelectTypeDelegate, HMProductListCollectionViewCellDelegate, HMAddCartWithSizeDelegate, HMProductDetailViewControllerdelegate>

@property (nonatomic, strong) UICollectionView *myCollectView;

@property (nonatomic, strong) NSArray *productArray;

@property (nonatomic, strong) NSArray *LastArray;

@property (nonatomic, strong) HMProductList *prolist;

@property (nonatomic, strong) HMSelectType *selectType;

@property (nonatomic, strong) HMSelectTitleView *titleVC;

@property (nonatomic, strong) UIButton *cartBtn;

@property (nonatomic, assign) NSInteger LastProSelectIndex;

@property (nonatomic, strong) HMLoginController *vc;

@property (nonatomic, strong) UILabel *numberOfShopPro;

@property (nonatomic, strong) HMAddCartWithSize *addCartWictSize;

@property (nonatomic, strong) HMNoDataReload *reload;

@property (nonatomic, assign) CGRect aframe;

@property (nonatomic, strong) UIImage *imageVI;
@end

@implementation HMProductListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpSubView];
    [self.RightBarItem setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [self.RightBarItem addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
}

- (void)search
{
    HMSearchController * vc = [[HMSearchController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setUpSubView {
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionHeadersPinToVisibleBounds = YES;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    self.myCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64) collectionViewLayout:flowLayout];
    self.myCollectView.delegate = self;
    self.myCollectView.dataSource = self;
    self.myCollectView.showsVerticalScrollIndicator = NO;
    self.myCollectView.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
    
    [self.myCollectView registerNib:[UINib nibWithNibName:NSStringFromClass([HMProductListCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"HMProductListCollectionViewCell"];
    [self.myCollectView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.view addSubview:self.myCollectView];
    
    [self getData:_dataArray[_selectIndex]];
    
    self.titleVC = [[HMSelectTitleView alloc] initWithFrame:CGRectMake((KWidthSCREEN - 115) / 2, 24, 115, 40)];
    self.titleVC.cate = _dataArray[_selectIndex];
    self.titleVC.delegate = self;
    [self.CustomNaviBar addSubview:_titleVC];
    
    _cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cartBtn.frame = CGRectMake(KWidthSCREEN - 65, KHeightSCREEN - 85, 45, 45);
    [_cartBtn setBackgroundImage:[UIImage imageNamed:@"ProductList_shopcart"] forState:UIControlStateNormal];
    [_cartBtn addTarget:self action:@selector(pushToCart) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cartBtn];
    
    _numberOfShopPro = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_cartBtn.frame) - 20, _cartBtn.frame.origin.y, 20, 20)];
    _numberOfShopPro.textColor = [UIColor whiteColor];
    _numberOfShopPro.text = [NSString stringWithFormat:@"%d", _CarNum];
    _numberOfShopPro.textAlignment = NSTextAlignmentCenter;
    _numberOfShopPro.layer.cornerRadius = 10;
    _numberOfShopPro.clipsToBounds = YES;
    _numberOfShopPro.font = [UIFont systemFontOfSize:12.0f];
    _numberOfShopPro.backgroundColor = [UIColor redColor];
    [self.view addSubview:_numberOfShopPro];
    
    [DataSingleton sharedPerson].refreshCartNum = ^{
        _numberOfShopPro.text = [NSString stringWithFormat:@"%@", [DataSingleton sharedPerson].cartNum];
    };
}

- (void)pushToCart {
    // 先判断有无存储账号信息
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        HMLoginController * login = [[HMLoginController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    } else {
        HMCartController *vc = [[HMCartController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
 
}

- (void)getData:(HomeCategoryDetail *)cate{
    //获取分类列表
    DefaultWeakSelf;
    [HttpBaseTool get:kChildList params:@{@"id":cate.id} success:^(id responseObj) {
        if (_reload !=nil) {
            [_reload removeFromSuperview];
        }
        _productArray = [HMProductModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
        self.prolist.selectIndex = _LastProSelectIndex = 0;
        _prolist.hidden = NO;
        [self getLastProduct];
    } failure:^(NSError *error) {
        _prolist.hidden = YES;
        weakSelf.reload.reloadData = ^void *{
            [weakSelf getData:weakSelf.dataArray[_selectIndex]];
            return nil;
        };
        [self.view addSubview:self.reload];
        [self.myCollectView reloadData];
    }];
}

- (void)getLastProduct {
    //获取详情列表
    HMProductModel *proModel = _productArray[_LastProSelectIndex];
    [HttpBaseTool get:KLastList params:@{@"id":[HMReductionData replaceNullValue:proModel.id]} success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            _LastArray = [HMLastPro mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
            [self.myCollectView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - collectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.LastArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HMProductListCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HMProductListCollectionViewCell" forIndexPath:indexPath];
    cell.proDuctModel = _LastArray[indexPath.row];
    cell.delegate = self;
    cell.index = indexPath;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HMProductDetailViewController *vc = [[HMProductDetailViewController alloc] init];
    HMLastPro *pro = _LastArray[indexPath.row];
    vc.pro_id = pro.id;
    vc.NavigationBarHidden= NO;
    vc.cartNumber = [[DataSingleton sharedPerson].cartNum intValue];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    NSLog(@"你点击了第%zd个分类",indexPath.item);
}

//- (void)refreshCartNumer {
//    _numberOfShopPro.text = [NSString stringWithFormat:@"%@", [DataSingleton sharedPerson].cartNum];
//}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        self.prolist.delegate = self;
        self.prolist.dataArray = _productArray;
        HomeCategoryDetail *cat = _productArray[_LastProSelectIndex];
        self.prolist.selectIndex = [cat.id integerValue];
        UICollectionReusableView * headerView = [self.myCollectView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        //        [headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        headerView.backgroundColor = [UIColor whiteColor];
        [headerView addSubview:self.prolist];
        return headerView;
    }
    return [self.myCollectView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){(KWidthSCREEN - 2)/3,170};
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (_prolist.hidden == YES) {
        return (CGSize){KWidthSCREEN,0};
    } else {
        return (CGSize){KWidthSCREEN,49};
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

#pragma mark - HMProductListDelegate
- (void)selectType:(HomeCategoryDetail *)Category selectIndex:(NSInteger)select{
//    self.titleVC.cate = Category;
    _LastProSelectIndex = select;
    [self getLastProduct];
}

#pragma mark - HMSelectTitleViewDelegate
- (void)changeType:(NSInteger)selectType {
    self.selectType.dataArray = _dataArray;
    self.selectType.delegate = self;
    if (!selectType) {
        [self.view addSubview:self.selectType];
    } else {
        [self.selectType removeFromSuperview];
    }
}
#pragma mark - HMSelectTypeDelegate
- (void)select:(HomeCategoryDetail *)cate {
    [self getData:cate];
    [self.selectType removeFromSuperview];
    self.titleVC.upAndDown = !self.titleVC.upAndDown;
    self.titleVC.cate = cate;
}

- (void)dismiss {
    [self.selectType removeFromSuperview];
    self.titleVC.upAndDown = !self.titleVC.upAndDown;
}

#pragma mark - HMProductListCollectionViewCellDelegate
- (void)sendIndex:(NSIndexPath *)index frame:(CGRect)frame  imageVI:(UIImage *)imageVI{
    if ([MGAccountTool getUsername].length == 0) {
        HMLoginController *vc = [[HMLoginController alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:nil];
    } else {
        HMLastPro *pro = _LastArray[index.row];
        
        if (pro.attr.count != 0) {
            self.addCartWictSize.index = index;
            _aframe = frame;
            _imageVI = imageVI;
            self.addCartWictSize.lastPro = _LastArray[index.row];
            [_addCartWictSize show];
        } else {
            _aframe = frame;
            _imageVI = imageVI;
            [self addCart:pro];
        }
    }
}

- (void)addCart:(HMLastPro *)lastPro {
    DefaultWeakSelf;
    NSDictionary *parm = @{@"user_tel":[MGAccountTool getTel], @"item_id":lastPro.id, @"item_number":@"1", @"item_price":lastPro.item_price, @"item_attr":@""};
    [HttpBaseTool post:kAddCart params:parm success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            LoginSuccess;
//            _CarNum++;
//            _numberOfShopPro.text = [NSString stringWithFormat:@"%d", _CarNum];

            [DataSingleton sharedPerson].refreshCartNum = ^{
                _numberOfShopPro.text = [NSString stringWithFormat:@"%@", [DataSingleton sharedPerson].cartNum];
                //        weakSelf.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
            };
            
            [HMHUDManager showHUDWithText:@"添加成功"];
            UIImageView *aimageVI = [[UIImageView alloc] initWithFrame:_aframe];
            aimageVI.image = _imageVI;
            [weakSelf.view addSubview:aimageVI];
            [UIView animateWithDuration:1.0 animations:^{
                aimageVI.frame = CGRectMake(KWidthSCREEN - 65 + 10, KHeightSCREEN - 85 + 10, 20, 20);
                aimageVI.alpha = 0.5;
            }];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [aimageVI removeFromSuperview];
            });
        } else {
            [HMHUDManager showHUDWithText:responseObj[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    }];

}


#pragma mark - HMAddCartWithSizeDelegate
- (void)getSelectSize:(NSArray *)sizeArray number:(NSString *)number {
    [_addCartWictSize dismiss];
    UIImageView *aimageVI = [[UIImageView alloc] initWithFrame:_aframe];
    aimageVI.image = _imageVI;
    [self.view addSubview:aimageVI];
//    _CarNum++;
//    _numberOfShopPro.text = [NSString stringWithFormat:@"%d", _CarNum];

    [DataSingleton sharedPerson].refreshCartNum = ^{
        _numberOfShopPro.text = [NSString stringWithFormat:@"%@", [DataSingleton sharedPerson].cartNum];
//        weakSelf.addCartView.numberOfCart = [[DataSingleton sharedPerson].cartNum integerValue];
    };
    [UIView animateWithDuration:1.0 animations:^{
        aimageVI.frame = CGRectMake(KWidthSCREEN - 65 + 10, KHeightSCREEN - 85 + 10, 20, 20);
        aimageVI.alpha = 0.5;
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [aimageVI removeFromSuperview];
    });
}

- (void)noLogin {
    HMLoginController * login = [[HMLoginController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:login];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (HMProductList *)prolist {
    if (_prolist == nil) {
        _prolist = [[HMProductList alloc] init];
    }
    return _prolist;
}

- (HMSelectType *)selectType {
    if (_selectType == nil) {
        _selectType = [[HMSelectType alloc] initWithFrame:CGRectZero dataArray:_dataArray];
    }
    return _selectType;
}

- (HMAddCartWithSize *)addCartWictSize {
//    if (_addCartWictSize == nil) {
        _addCartWictSize = [[HMAddCartWithSize alloc] init];
        _addCartWictSize.delegate = self;
//    }
    return _addCartWictSize;
}

- (HMNoDataReload *)reload {
    if (_reload == nil) {
        _reload = [[HMNoDataReload alloc] init];
    }
    return _reload;
}

@end
